package com.bangmai.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTP;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.helpers.FormattingTuple;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.stereotype.Component;

import com.bangmai.beans.Order2CommodityInspection;
import com.bangmai.beans.Order2Customer;
import com.bangmai.beans.Order2Immigration;
import com.bangmai.beans.Order2Payment;
import com.bangmai.beans.Order2StockOut;
import com.bangmai.beans.OrderBody2Payment;
import com.bangmai.beans.OrderGood2CommodityInspection;
import com.bangmai.beans.OrderGood2Customer;
import com.bangmai.beans.OrderGood2Immigration;
import com.bangmai.beans.OrderGood2StockOut;
import com.bangmai.config.Config;

/**
 * XML操作工具类
 * 
 * @author dellpc
 *
 */
@Component
public class XmlUtil {
	private static Logger logger = Logger.getLogger(XmlUtil.class.getName());

	/**
	 * 海关 创建报文并发送报文
	 * 
	 * @param order2Customer
	 * @param goods
	 */

	public void createCustomXml(Order2Customer order2Customer, List<OrderGood2Customer> goods) {
		if (goods == null || goods.isEmpty()) {
			logger.info("订单信息中没有商品信息");
			return;
		}

		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order2Customer.MessageID));
		head.addContent(new Element("MessageType").setText(order2Customer.MessageType));
		head.addContent(new Element("SenderID").setText(order2Customer.SenderID));
		head.addContent(new Element("SendTime").setText(order2Customer.SendTime));
		head.addContent(new Element("Version").setText(order2Customer.Version));
		root.addContent(head);

		Element Declaration = new Element("Declaration");
		Element EOrder = new Element("EOrder");
		EOrder.addContent(new Element("OrderId").setText(order2Customer.OrderId));
		EOrder.addContent(new Element("IEFlag").setText(order2Customer.IEFlag));
		EOrder.addContent(new Element("OrderStatus").setText(order2Customer.OrderStatus));
		EOrder.addContent(new Element("EntRecordNo").setText(order2Customer.EntRecordNo));
		EOrder.addContent(new Element("EntRecordName").setText(order2Customer.EntRecordName));
		EOrder.addContent(new Element("OrderName").setText(order2Customer.OrderName));
		EOrder.addContent(new Element("OrderDocType").setText(order2Customer.OrderDocType));
		EOrder.addContent(new Element("OrderDocId").setText(order2Customer.OrderDocId));
		EOrder.addContent(new Element("OrderPhone").setText(order2Customer.OrderPhone));
		EOrder.addContent(new Element("OrderGoodTotal").setText(order2Customer.OrderGoodTotal));
		EOrder.addContent(new Element("OrderGoodTotalCurr").setText(order2Customer.OrderGoodTotalCurr));
		EOrder.addContent(new Element("Freight").setText(order2Customer.Freight));
		EOrder.addContent(new Element("FreightCurr").setText(order2Customer.FreightCurr));
		EOrder.addContent(new Element("Tax").setText(order2Customer.Tax));
		EOrder.addContent(new Element("TaxCurr").setText(order2Customer.TaxCurr));
		EOrder.addContent(new Element("Note").setText(order2Customer.Note));
		EOrder.addContent(new Element("OrderDate").setText(order2Customer.OrderDate));
		Declaration.addContent(EOrder);
		root.addContent(Declaration);

		Element EOrderGoods = new Element("EOrderGoods");

		for (int i = 0; i < goods.size(); i++) {

			Element EOrderGood = new Element("EOrderGood");
			EOrderGood.addContent(new Element("GNo").setText(goods.get(i).GNo));
			EOrderGood.addContent(new Element("ChildOrderNo").setText(goods.get(i).ChildOrderNo));
			EOrderGood.addContent(new Element("StoreRecordNo").setText(goods.get(i).StoreRecordNo));
			EOrderGood.addContent(new Element("StoreRecordName").setText(goods.get(i).StoreRecordName));
			EOrderGood.addContent(new Element("CustomsListNO").setText(goods.get(i).CustomsListNO));
			EOrderGood.addContent(new Element("DecPrice").setText(goods.get(i).DecPrice));
			EOrderGood.addContent(new Element("Unit").setText(goods.get(i).Unit));
			EOrderGood.addContent(new Element("GQty").setText(goods.get(i).GQty));
			EOrderGood.addContent(new Element("DeclTotal").setText(goods.get(i).DeclTotal));
			EOrderGood.addContent(new Element("Notes").setText(goods.get(i).Notes));
			EOrderGoods.addContent(EOrderGood);
		}
		Declaration.addContent(EOrderGoods);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = Config.CUSTOM_IN;
		logger.info(filepath);

		String filename = order2Customer.MessageType + FileUtil.getTimeString2() + "_" + FileUtil.get3RandomString()
				+ ".xml";
		logger.info(filename);
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + filename));

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			xmlOutputter = null;
		}
		String xmlString = null;
		try {
			xmlString = FileUtil.readFile(filepath + filename);

			AESMessageSigner signer = new AESMessageSigner();
			xmlString = signer.encrypt(xmlString.getBytes());
			

		} catch (Exception e) {
			e.getMessage();
		}
		FileWriter writer = null;
		try {
			// ��ԭ�е�������� Ȼ������ı����ȥ
			File file = new File(filepath + filename);
			writer = new FileWriter(file);
			writer.write("");
			FileUtil.saveFile(filepath + filename, xmlString);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		logger.info("开始上传报文。。。");

		boolean isSuccess = false;
		try {
			isSuccess = FTPClientUtil.transferFile(Config.FTP_CUSTOM_HOST, Config.FTP_CUSTOM_PORT,
					Config.FTP_CUSTOM_USERNAME, Config.FTP_CUSTOM_PASSWORD, Config.FTP_CUSTOM_DOWNLOAD_FILEPATH, true,
					filepath + filename, "", "");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (isSuccess) {
			logger.info("报文上传成功");

		} else {
			logger.info("报文上传失败");
		}

	}

	/**
	 * 商检 创建报文和发送报文
	 * 
	 * @param goods
	 *            ��Ʒ
	 * @param order
	 *            ����
	 */

	public void createCommodityInspectionXml(Order2CommodityInspection order,
			List<OrderGood2CommodityInspection> goods) {
		if (goods == null || goods.isEmpty()) {
			logger.info("订单信息中没有商品信息");
			return;
		}
		Element root = new Element("ROOT");
		Document document = new Document(root);
		Element head = new Element("Head");
		// 报文头
		head.addContent(new Element("MessageID").setText(order.getMessageID()));
		head.addContent(new Element("MessageType").setText(order.getMessageType()));
		head.addContent(new Element("Receiver").setText(order.getReceiver()));
		head.addContent(new Element("Sender").setText(order.getSender()));
		head.addContent(new Element("SendTime").setText(order.getSendTime()));
		head.addContent(new Element("FunctionCode").setText(order.getFunctionCode()));
		head.addContent(new Element("Version").setText(order.getVersion()));
		root.addContent(head);
		logger.info("头部创建完成");
		Element body = new Element("Body");
		Element swbebtrade = new Element("swbebtrade");
		Element record = new Element("Record");
		// body �ж�����Ϣ
		record.addContent(new Element("EntInsideNo").setText(order.getEntInsideNo()));
		record.addContent(new Element("Ciqbcode").setText(order.getCiqbcode()));
		record.addContent(new Element("CbeComcode").setText(order.getCbeComcode()));
		record.addContent(new Element("CbepComcode").setText(order.getCbepComcode()));
		record.addContent(new Element("OrderStatus").setText(order.getOrderStatus()));
		record.addContent(new Element("ReceiveName").setText(order.getReceiveName()));
		record.addContent(new Element("ReceiveAddr").setText(order.getReceiveAddr()));
		record.addContent(new Element("ReceiveNo").setText(order.getReceiveNo()));
		record.addContent(new Element("ReceivePhone").setText(order.getReceivePhone()));
		record.addContent(new Element("FCY").setText(order.getFCY()));
		record.addContent(new Element("Fcode").setText(order.getFcode()));
		record.addContent(new Element("Editccode").setText(order.getEditccode()));
		record.addContent(new Element("DrDate").setText(order.getDrDate()));
		swbebtrade.addContent(record);
		body.addContent(swbebtrade);
		root.addContent(body);
		logger.info("body创建完成");
		Element swbebtrade_good = new Element("swbebtradeg");
		for (int i = 0; i < goods.size(); i++) {
			Element Record = new Element("Record");
			Record.addContent(new Element("EntGoodsNo").setText(goods.get(i).getEntGoodsNo()));
			Record.addContent(new Element("Gcode").setText(goods.get(i).getGcode()));
			Record.addContent(new Element("Hscode").setText(goods.get(i).getHscode()));
			Record.addContent(new Element("CiqGoodsNo").setText(goods.get(i).getCiqGoodsNo()));
			Record.addContent(new Element("CopGName").setText(goods.get(i).getCopGName()));
			Record.addContent(new Element("Brand").setText(goods.get(i).getBrand()));
			Record.addContent(new Element("Spec").setText(goods.get(i).getSpec()));
			Record.addContent(new Element("Origin").setText(goods.get(i).getOrigin()));
			Record.addContent(new Element("Qty").setText(goods.get(i).getQty()));
			Record.addContent(new Element("QtyUnit").setText(goods.get(i).getQtyUnit()));
			Record.addContent(new Element("DecPrice").setText(goods.get(i).getDecPrice()));
			Record.addContent(new Element("DecTotal").setText(goods.get(i).getDecTotal()));
			Record.addContent(new Element("SellWebSite").setText(goods.get(i).getSellWebSite()));
			Record.addContent(new Element("Nots").setText(goods.get(i).getNots()));
			swbebtrade_good.addContent(Record);
		}
		record.addContent(swbebtrade_good);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = Config.CCIQ_IN;
		logger.info(filepath);

		String filename = order.MessageType + "_" + FileUtil.getTimeString2() + "_" + FileUtil.get3RandomString()
				+ ".xml";
		logger.info(filename);
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + filename));
			logger.info("报文创建完成");
			String packetXml = FileUtil.readFile(filepath + filename);
			packetXml = packetXml.replace("<FunctionCode />", "<FunctionCode></FunctionCode>");
			packetXml = packetXml.replace("<Nots />", "<Nots></Nots>");
			packetXml = packetXml.replace("<CiqGoodsNo />", "<CiqGoodsNo></CiqGoodsNo>");
			// 将原来的 XML文件内容清空
			File file = new File(filepath + filename);
			FileWriter writer = new FileWriter(file);
			writer.write("");
			FileUtil.saveFile(filepath + filename, packetXml);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			fm = null;
			xmlOutputter = null;
		}

		boolean isSuccess = false;
		try {
			isSuccess = FTPClientUtil.transferFile(Config.FTP_CCIQ_IP, Config.FTP_CCIQ_PORT, Config.FTP_CCIQ_USERNAME,
					Config.FTP_CCIQ_PASSWORD, Config.FTP_CCIQ_UPLOADPATH, true, filepath + filename, "", "");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (isSuccess) {
			logger.info("上传成功");
		} else {
			logger.info("上传失败");
		}
	}

	/**
	 * 支付
	 * 
	 * @param oPayment
	 *            ����ͷ
	 * @param list
	 *            ��������
	 */

	public void createPaymentXml(Order2Payment oPayment, List<OrderBody2Payment> list) {
		if (oPayment == null || list.isEmpty()) {
			return;
		}
		Element root = new Element("VnbMessage");
		Document document = new Document(root);

		Element MessageHead = new Element("MessageHead");
		MessageHead.addContent(new Element("MessageCode").setText(oPayment.getMessageCode()));
		MessageHead.addContent(new Element("MessageID").setText(oPayment.getMessageID()));
		MessageHead.addContent(new Element("SenderID").setText(oPayment.getSenderID()));
		MessageHead.addContent(new Element("SendTime").setText(oPayment.SendTime));
		MessageHead.addContent(new Element("Sign").setText(oPayment.getSign()));
		root.addContent(MessageHead);

		Element MessageBodyList = new Element("MessageBodyList");
		for (int i = 0; i < list.size(); i++) {
			Element MessageBody = new Element("MessageBody");
			MessageBody.addContent(new Element("customICP").setText(list.get(i).getCustomICP()));
			MessageBody.addContent(new Element("ciqType").setText(list.get(i).getCiqType()));
			MessageBody.addContent(new Element("cbepComCode").setText(list.get(i).getCbepComCode()));
			MessageBody.addContent(new Element("orderNo").setText(list.get(i).getOrderNo()));
			MessageBody.addContent(new Element("payTransactionNo").setText(list.get(i).getPayTransactionNo()));
			MessageBody.addContent(new Element("payChnlID").setText(list.get(i).getPayChnlID()));
			MessageBody.addContent(new Element("payTime").setText(list.get(i).getPayTime()));
			MessageBody.addContent(new Element("payGoodsAmount").setText(list.get(i).getPayGoodsAmount()));
			MessageBody.addContent(new Element("payTaxAmount").setText(list.get(i).getPayTaxAmount()));
			MessageBody.addContent(new Element("freight").setText(list.get(i).getFreight()));
			MessageBody.addContent(new Element("payCurrency").setText(list.get(i).getPayCurrency()));
			MessageBody.addContent(new Element("payerName").setText(list.get(i).getPayerName()));
			MessageBody.addContent(new Element("payerDocumentType").setText(list.get(i).getPayerDocumentType()));
			MessageBody.addContent(new Element("payerDocumentNumber").setText(list.get(i).getPayerDocumentNumber()));
			MessageBodyList.addContent(MessageBody);
		}
		root.addContent(MessageBodyList);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = Config.PAY_LOCALFILRPATH;

		String filename = FileUtil.getTimeString2() + "_" + FileUtil.get4RandomString() + ".xml";
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + filename));

			logger.info("XML文件创建完成");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			fm = null;
			xmlOutputter = null;
		}
		try {
			update(filepath + filename);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			HttpRequestUtils.post(FileUtil.readFile(filepath + filename).getBytes(), Config.PAY_URL,
					Config.PAY_LOCALFILRPATH + filename);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取签名字段 sign
	 * 
	 * @param filepath
	 * @return
	 */

	public String getSign(String filepath) {
		String packetXmlString = null;

		try {
			packetXmlString = FileUtil.readFile(filepath);
			packetXmlString = packetXmlString.replace("<Sign />", "<Sign></Sign>");
			System.out.println(packetXmlString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int begin_index = packetXmlString.indexOf("<?");
		int end_index = packetXmlString.indexOf(">");
		String head = packetXmlString.substring(begin_index, end_index + 1);
		packetXmlString = packetXmlString.replace(head, "");// ȥ��XMLͷ����

		String sign = null;
		try {
			sign = Md5Util.getMD5ofByte((packetXmlString + Config.PAY_KEY).getBytes("utf-8"));
			sign = Md5Util.getMD5ofByte(sign.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // ����ͷ sign�ֶε�ֵ
		logger.info("sign:" + sign);
		return sign;
	}

	// ��doc����������ļ�
	public static void saveXML(Document doc, String filepath) {

		try {
			// ����xml�ļ������
			XMLOutputter xmlopt = new XMLOutputter();

			// �����ļ������
			FileWriter writer = new FileWriter(filepath);

			// ָ���ĵ���ʽ
			Format fm = Format.getPrettyFormat();
			fm.setEncoding("utf-8");
			xmlopt.setFormat(fm);
			// ��docд�뵽ָ�����ļ���
			xmlopt.output(doc, writer);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * x修改某一个节点的值
	 * 
	 * @param filepath
	 *            文件全路径
	 * @param sign
	 *            节点名字
	 */
	public void updateXml(String filepath, String sign) {
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = null;
		try {
			document = saxBuilder.build(new File(filepath));
			Element root = document.getRootElement();
			Element element = root.getChild("MessageHead");
			Element element2 = element.getChild("Sign");
			System.out.println(element2.getName());
			element2.setText(sign);

		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		saveXML(document, filepath);

	}

	// 填充签名
	public void update(String filePath) throws IOException {
		String packetXmlString = FileUtil.readFile(filePath);
		packetXmlString = packetXmlString.replace("<Sign />", "<Sign></Sign>");
		System.out.println(packetXmlString);
		int begin_index = packetXmlString.indexOf("<?");
		int end_index = packetXmlString.indexOf(">");
		String head = packetXmlString.substring(begin_index, end_index + 1);
		packetXmlString = packetXmlString.replace(head, "");// 去掉XML头申明
		String signXML = Md5Util.getMD5ofByte((packetXmlString + Config.PAY_KEY).getBytes("utf-8"));// 报文头
																									// sign字段的值ֵ
		packetXmlString = head + packetXmlString.replace("<Sign></Sign>", "<Sign>" + signXML + "</Sign>");
		System.out.println(packetXmlString);
		// 将原来的 XML文件内容清空
		File file = new File(filePath);
		FileWriter writer = new FileWriter(file);
		writer.write("");
		FileUtil.saveFile(filePath, packetXmlString);
	}

	/**
	 * 出库 创建报文并发送
	 * 
	 * @param order
	 * @param goods
	 */
	public void createStockOutXml(Order2StockOut order, List<OrderGood2StockOut> goods) {
		if (goods == null || goods.isEmpty()) {
			logger.info("订单中没有商品信息");
			return;
		}

		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order.MessageID));
		head.addContent(new Element("FunctionCode").setText(order.FunctionCode));
		head.addContent(new Element("MessageType").setText(order.MessageType));
		head.addContent(new Element("SenderID").setText(order.SenderID));
		head.addContent(new Element("SendTime").setText(order.SendTime));
		root.addContent(head);

		Element Declaration = new Element("Declaration");
		Element ExOrder = new Element("ExOrder");
		ExOrder.addContent(new Element("EntInsideNo").setText(order.EntInsideNo));
		ExOrder.addContent(new Element("InputDate").setText(order.InputDate));
		ExOrder.addContent(new Element("DrDate").setText(order.DrDate));
		ExOrder.addContent(new Element("Nots").setText(order.Nots));
		ExOrder.addContent(new Element("IEFlag").setText(order.IEFlag));
		ExOrder.addContent(new Element("NetWt").setText(order.NetWt));
		ExOrder.addContent(new Element("GrossWt").setText(order.GrossWt));
		ExOrder.addContent(new Element("Num").setText(order.Num));
		ExOrder.addContent(new Element("GoodInfo").setText(order.GoodInfo));
		ExOrder.addContent(new Element("RecipientName").setText(order.RecipientName));
		ExOrder.addContent(new Element("RecipientCountryCode").setText(order.RecipientCountryCode));
		ExOrder.addContent(new Element("RecipientProvincesCode").setText(order.RecipientProvincesCode));
		ExOrder.addContent(new Element("RecipientDetailedAddress").setText(order.RecipientDetailedAddress));
		ExOrder.addContent(new Element("RecipientPhone").setText(order.RecipientPhone));
		ExOrder.addContent(new Element("ReceiveNo").setText(order.ReceiveNo));
		ExOrder.addContent(new Element("OrderName").setText(order.OrderName));
		ExOrder.addContent(new Element("OrderDocType").setText(order.OrderDocType));
		ExOrder.addContent(new Element("OrderDocId").setText(order.OrderDocId));
		ExOrder.addContent(new Element("OrderId").setText(order.OrderId));
		ExOrder.addContent(new Element("OrderEntRecordNo").setText(order.OrderEntRecordNo));
		ExOrder.addContent(new Element("ExpressCo").setText(order.ExpressCo));
		ExOrder.addContent(new Element("CiqBusiMode").setText(order.CiqBusiMode));
		ExOrder.addContent(new Element("CiqEnorderCode").setText(order.CiqEnorderCode));
		ExOrder.addContent(new Element("CiqBcode").setText(order.CiqBcode));
		ExOrder.addContent(new Element("CiqFcy").setText(order.CiqFcy));
		ExOrder.addContent(new Element("CiqCbeComcode").setText(order.CiqCbeComcode));
		ExOrder.addContent(new Element("CiqCbepcomcode").setText(order.CiqCbepcomcode));
		ExOrder.addContent(new Element("ExpressProv").setText(order.ExpressProv));
		ExOrder.addContent(new Element("ExpressCity").setText(order.ExpressCity));
		ExOrder.addContent(new Element("ExpressArea").setText(order.ExpressArea));
		ExOrder.addContent(new Element("ExpressRemarks").setText(order.ExpressRemarks));
		ExOrder.addContent(new Element("NeedList").setText(order.NeedList));
		ExOrder.addContent(new Element("NeedInvoice").setText(order.NeedInvoice));
		ExOrder.addContent(new Element("InvoiceType").setText(order.InvoiceType));
		ExOrder.addContent(new Element("InvoiceTitle").setText(order.InvoiceTitle));
		ExOrder.addContent(new Element("InvoiceContent").setText(order.InvoiceContent));
		ExOrder.addContent(new Element("CiqPayComcode").setText(order.CiqPayComcode));
		ExOrder.addContent(new Element("CiqPayno").setText(order.CiqPayno));
		ExOrder.addContent(new Element("CiqPayorName").setText(order.CiqPayorName));
		ExOrder.addContent(new Element("CiqPayFcy").setText(order.CiqPayFcy));
		ExOrder.addContent(new Element("CiqPayFcode").setText(order.CiqPayFcode));
		ExOrder.addContent(new Element("CiqPayDate").setText(order.CiqPayDate));
		ExOrder.addContent(new Element("Freight").setText(order.Freight));
		ExOrder.addContent(new Element("ValuationFee").setText(order.ValuationFee));
		ExOrder.addContent(new Element("ExpressNo").setText(order.ExpressNo));
		ExOrder.addContent(new Element("NeedWmsOper").setText(order.NeedWmsOper));
		ExOrder.addContent(new Element("LogisticsProviders").setText(order.LogisticsProviders));
		ExOrder.addContent(new Element("CustomerCode").setText(order.CustomerCode));
		ExOrder.addContent(new Element("InternetDomainName").setText(order.InternetDomainName));
		ExOrder.addContent(new Element("CustomConsigneePhoneNumber").setText(order.CustomConsigneePhoneNumber));
		ExOrder.addContent(new Element("CustomConsigneeCountryCode").setText(order.CustomConsigneeCountryCode));
		ExOrder.addContent(new Element("CustomTransportTypeCode").setText(order.CustomTransportTypeCode));
		ExOrder.addContent(new Element("TransportName").setText(order.TransportName));
		ExOrder.addContent(new Element("CustomPackagingTypeCodep").setText(order.CustomPackagingTypeCode));
		ExOrder.addContent(new Element("CustomAgentCode").setText(order.CustomAgentCode));
		ExOrder.addContent(new Element("CustomAgentName").setText(order.CustomAgentName));
		Declaration.addContent(ExOrder);
		root.addContent(Declaration);

		Element GoodsLists = new Element("GoodsLists");
		for (int i = 0; i < goods.size(); i++) {
			Element Goods = new Element("Goods");
			Goods.addContent(new Element("GoodsNo").setText(goods.get(i).GoodsNo));
			Goods.addContent(new Element("Qty").setText(goods.get(i).Qty));
			Goods.addContent(new Element("DecPrice").setText(goods.get(i).DecPrice));
			Goods.addContent(new Element("DecTotal").setText(goods.get(i).DecTotal));
			Goods.addContent(new Element("GrossWt").setText(goods.get(i).GrossWt));
			Goods.addContent(new Element("NetWt").setText(goods.get(i).NetWt));
			Goods.addContent(new Element("Nots").setText(goods.get(i).Nots));
			Goods.addContent(new Element("GoodsBatchNo").setText(goods.get(i).GoodsBatchNo));
			Goods.addContent(new Element("CustomConversionFactor").setText(goods.get(i).CustomConversionFactor));
			Goods.addContent(new Element("CustomOriginCountryCode").setText(goods.get(i).CustomOriginCountryCode));
			GoodsLists.addContent(Goods);
		}
		Declaration.addContent(GoodsLists);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = Config.WL_STOCKOUT_LOCALFILEPATH_IN;
		logger.info(filepath);
		String filename = FileUtil.getTimeString2() + "_" + FileUtil.get3RandomString() + ".xml";
		logger.info(filename);
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + filename));
			logger.info("报文创建完成");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			xmlOutputter = null;
		}

		logger.info("开始上传报文。。。");

		boolean isSuccess = false;
		try {
			isSuccess = FTPClientUtil.transferFile(Config.STOCKOUT_IP, Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
					Config.STOCKOUT_PASSWORD, Config.STOCKOUT_UPLOAD_FILEPATH, true, filepath + filename, "", "");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (isSuccess) {
			logger.info("报文上传成功");

		} else {
			logger.info("报文上传失败");
		}

	}

	/**
	 * 物流 入库
	 * 
	 * @param order
	 * @param list
	 */

	public void createImmigrationXml(Order2Immigration order, List<OrderGood2Immigration> list) {
		if (list == null || list.isEmpty()) {
			logger.info("订单中没有商品信息");

		}
		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order.MessageID));
		head.addContent(new Element("FunctionCode").setText(order.FunctionCode));
		head.addContent(new Element("MessageType").setText(order.MessageType));
		head.addContent(new Element("SenderID").setText(order.SenderID));
		head.addContent(new Element("SendTime").setText(order.SendTime));
		root.addContent(head);
		Element Declaration = new Element("Declaration");
		Element InOrder = new Element("InOrder");
		InOrder.addContent(new Element("EntInsideNo").setText(order.EntInsideNo));
		InOrder.addContent(new Element("InputDate").setText(order.InputDate));
		InOrder.addContent(new Element("DrDate").setText(order.DrDate));
		InOrder.addContent(new Element("Nots").setText(order.Nots));
		InOrder.addContent(new Element("CountryCode").setText(order.CountryCode));
		InOrder.addContent(new Element("Ciqbcode").setText(order.Ciqbcode));
		InOrder.addContent(new Element("CiqBargainnoo").setText(order.CiqBargainnoo));
		InOrder.addContent(new Element("CiqShippername").setText(order.CiqShippername));
		InOrder.addContent(new Element("CiqConsigneename").setText(order.CiqConsigneename));
		InOrder.addContent(new Element("CiqPortload").setText(order.CiqPortload));
		InOrder.addContent(new Element("CiqPortdis").setText(order.CiqPortdis));
		InOrder.addContent(new Element("CiqTradecode").setText(order.CiqTradecode));
		InOrder.addContent(new Element("CiqCountryload").setText(order.CiqCountryload));
		InOrder.addContent(new Element("CiqCbeComcode").setText(order.CiqCbeComcode));
		InOrder.addContent(new Element("BillNo").setText(order.BillNo));
		InOrder.addContent(new Element("Tool").setText(order.Tool));
		InOrder.addContent(new Element("LogisticsProviders").setText(order.LogisticsProviders));
		InOrder.addContent(new Element("CustomerCode").setText(order.CustomerCode));
		InOrder.addContent(new Element("CiqCtType").setText(order.CiqCtType));
		InOrder.addContent(new Element("CtNumber").setText(order.CtNumber));
		InOrder.addContent(new Element("CarNo").setText(order.CarNo));
		InOrder.addContent(new Element("TransportMode").setText(order.TransportMode));
		Declaration.addContent(InOrder);
		root.addContent(Declaration);

		Element GoodsLists = new Element("GoodsLists");

		for (int i = 0; i < list.size(); i++) {
			Element Goods = new Element("Goods");
			Goods.addContent(new Element("GoodsNo").setText(list.get(i).GoodsNo));
			Goods.addContent(new Element("Qty").setText(list.get(i).Qty));
			Goods.addContent(new Element("DecPrice").setText(list.get(i).DecPrice));
			Goods.addContent(new Element("DecTotal").setText(list.get(i).DecTotal));
			Goods.addContent(new Element("GrossWt").setText(list.get(i).GrossWt));
			Goods.addContent(new Element("NetWt").setText(list.get(i).NetWt));
			Goods.addContent(new Element("Nots").setText(list.get(i).Nots));
			Goods.addContent(new Element("CiqPacktype").setText(list.get(i).CiqPacktype));
			Goods.addContent(new Element("CiqBuyfromcity").setText(list.get(i).CiqBuyfromcity));
			Goods.addContent(new Element("CiqGoodsbatchno").setText(list.get(i).CiqGoodsbatchno));
			Goods.addContent(new Element("CiqCtSize").setText(list.get(i).CiqCtSize));
			Goods.addContent(new Element("CiqCtType").setText(list.get(i).CiqCtType));
			Goods.addContent(new Element("CtNumber").setText(list.get(i).CtNumber));
			Goods.addContent(new Element("BarCode").setText(list.get(i).BarCode));
			Goods.addContent(new Element("FirstStatutoryUnitCode").setText(list.get(i).FirstStatutoryUnitCode));
			Goods.addContent(new Element("FirstStatutoryQuantity").setText(list.get(i).FirstStatutoryQuantity));
			GoodsLists.addContent(Goods);
		}
		Declaration.addContent(GoodsLists);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = Config.WL_IMMIGRATION_LOCALFILEPATH_IN;
		logger.info(filepath);
		String filename = FileUtil.getTimeString2() + "_" + FileUtil.get3RandomString() + ".xml";
		logger.info(filename);
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + filename));
			logger.info("报文创建完成");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			xmlOutputter = null;
		}

		logger.info("开始上传报文。。。");
		boolean isSuccess = false;
		try {
			isSuccess = FTPClientUtil.transferFile(Config.STOCKOUT_IP, Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
					Config.STOCKOUT_PASSWORD, Config.STOCKOUT_UPLOAD_FILEPATH, true, filepath + filename, "", "");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (isSuccess) {
			logger.info("报文上传成功");

		} else {
			logger.info("报文上传失败");
		}

	}

	/**
	 * 获取远程FTP目录下的文件
	 * 
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @param localFilePath
	 * @param remoteFilePath
	 * @throws Exception
	 */

	public boolean downloadXml(String ip, String port, String username, String password, String localFilePath,
			String remoteFilePath, String fileName) throws Exception {
		boolean isSuccess = FTPClientUtil.downloadFile(ip, Integer.valueOf(port), username, password, remoteFilePath,
				fileName, localFilePath);
		parserCustomXml(localFilePath);
		return isSuccess;
	}

	/**
	 * 解析回执报文
	 * 
	 * @param localPath
	 * @param element
	 */
	public void parserCustomXml(String localPath) throws Exception {
		File file = new File(localPath);
		File[] files = file.listFiles();
		if (files != null && files.length > 0) {
			int len = files.length;
			for (int i = 0; i < len; i++) {
				File file_ = new File(localPath + File.separator + files[i].getName());
				if (file_.getName().endsWith(".txt")) {
					String fileName = file_.getName();
					fileName = fileName.replace(".txt", ".xml");
					file_.renameTo(new File(localPath + File.separator + fileName));
					String receiverXMl = null;
					receiverXMl = FileUtil.readFile(localPath + File.separator + fileName);

					receiverXMl = AESMessageSigner.decrypt(receiverXMl);
					// 将原来的 XML文件内容清空

					File file1 = new File(localPath + "/" + fileName);
					FileWriter writer = new FileWriter(file1);
					writer.write("");
					writer.close();
					file=null;
					FileUtil.saveFile(localPath + "/" + fileName, receiverXMl);
					

				}
			}

		}

	}

	/**
	 * 解析XML文件
	 * 
	 * @param localPath
	 * @param element
	 * @throws JDOMException
	 * @throws IOException
	 */

	public void parserXml(String localPath, String element) throws JDOMException, IOException {
		File file = new File(localPath);
		File[] files = file.listFiles();
		if (files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				SAXBuilder builder = new SAXBuilder();
				Document document = builder.build(localPath + "/" + f.getName());
				Element root = document.getRootElement();
				List persons = root.getChildren(element);
				if (!persons.isEmpty()) {
					for (int j = 0; j < persons.size(); j++) {
						Element person = (Element) persons.get(j);
						List pros = person.getChildren();
						if (!pros.isEmpty()) {
							for (int m = 0; m < pros.size(); m++) {
								Element element_ = (Element) pros.get(m);
								System.out.println(element_.getName() + "->>>" + element_.getValue());
							}
						} else {
							System.out.println(person.getName() + "--" + person.getValue());
						}

					}
				}

			}

		}

	}

	/**
	 * 移除指定路径下所有文件
	 * 
	 * @param strPath
	 */
	public  void removeAllFile(String strPath) {
		
		File file = new File(strPath);
		if (!file.exists()) {
			
			return;
		}
		if (!file.isDirectory()) {
			
			return;
		}
		String[] fileList = file.list();
		File tempFile = null;
		for (int i = 0; i < fileList.length; i++) {
			if (strPath.endsWith(File.separator)) {
				tempFile = new File(strPath + fileList[i]);
			} else {
				tempFile = new File(strPath + File.separator + fileList[i]);
			}
			if (tempFile.isFile()) {
				logger.info("删除文件"+tempFile.getName());
				if(tempFile.canExecute())
				tempFile.delete();
			}
			if (tempFile.isDirectory()) {
				removeAllFile(strPath + "/" + fileList[i]);// 删除文件夹里面的文件
				// removeFolder(strPath + "/" + fileList[i]);// 删除文件夹
			}
		}
	}
}
